/* 增删改查处理对象
 * @Author: kehua.lsy
 * @Date: 2019-11-19 15:11:21
 * @Last Modified by:   Administrator
 * @Last Modified time: 2019-11-19 15:11:21
 */
const Crud = {
  data () {
    return {
      request: {
        getMethods: '',                                        //获得列表 方法
        editMethods: '',                                       //编辑列表 方法
        addMethods: '',                                        //添加数据 方法
        delMethods: '',                                        //删除数据 方法
      },
      url: {
        getData: '',                                           //获取列表的URL
        delData: '',                                           //删除列表的URL
        editData: '',                                          //编辑数据的URL
        addData: ''                                            //添加数据的URL
      },
      dataListField: 'list',                                   //数据list取值字段
      tableInfos: [],                                          //表格属性信息
      tableData: [],                                           //表格数据
      multipleSelection: [],                                   //多选对象
      buttonControls: [],                                      //是否控制按钮show disabled
      searchFormInfos: {},                                     //查询表单数据
      addFormInfos: {},                                        //新增表单数据
      searchFields: {},                                        //查询参数
      addFields: {},                                           //新增参数
      baseData: {},                                            //处理过的基础数据
      originBaseData: {},                                      //原始的基础数据
      pageNum: 1,                                              //当前页码，设置页码为 0 表示获取所有数据
      pageSizes: [10, 50, 100, 200],                           //每页显示多少条数据
      pageSize: 10,                                            //当前显示每页多少条数据
      pageCount: 0,                                            //总共几页
      total: 0,                                                //数据总条数
      interval: 10000,                                         //定时取数据，默认10000毫秒
      rowNum: -1,                                              //当前编辑的行
      dialogFormVisible: false,                                //是否显示对话框
      isEdit: false,                                           //是否是编辑
      isOpenInterval: false,                                   //是否开启定时取数据
      isPager: true,                                           //是否分页
      timer: null,
      layout: "total, sizes, prev, pager, next, jumper",       //配置显示的选项
      delProp: 'id'                                            //用于删除的字段
    }
  },
  methods: {
    //增 改
    handleSave (val) {
      let Methods = this.isEdit ? this.request.editMethods : this.request.addMethods
      api[Methods](this.addFields).then((res) => {
        console.log(res)
        this.handleSearchByStatus(res)
        this.dialogFormVisible = false
      }).catch((res) => {
        this.$_c.msg(res.message, { type: 'error' })
      })

    },

    //删
    handleDelete (val) {
      const info = '此操作将删除该记录，确认继续？'
      this.$_c.messageBoxComfirm(info).then((res) => {
        if (res === 0) {
          let ids = [val.data[this.delProp]].join(',')
          api[this.request.delMethods]({ [this.delProp + 's']: ids }).then(res => {
            this.handleSearchByStatus(res)
          })
        }
      })
    },

    //查
    handleSearch () {
      this.loading = true
      //生成请求参数
      let data = Object.assign({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }, this.searchFields)
      api[this.request.getMethods](data).then((res) => {
        // 表格数据赋值
        this.tableData = this.isPager ? res.data[this.dataListField] : res.data;
        // 分页赋值
        this.pageParam.currentPage = res.data.pageNum ? res.data.pageNum : 0;
        this.formInline.pageSize = res.data.pageSize ? res.data.pageSize : 0;
        this.pageParam.total = res.data.total ? res.data.total : 0;
        // 加载结束
        this.loading = false
        //获取数据后对数据进行修饰
        this.handleSearchSuccess && this.handleSearchSuccess()
      }).catch(error => {
        this.tableData = []
        this.loading = false
      })
    },

    //处理批量删除
    handleBatchDelete () {
      const info = '此操作将批量删除所选记录，确认继续？'
      this.$_c.messageBoxComfirm(info).then((res) => {
        if (res === 0) {
          let ids = []
          for (let item of this.multipleSelection) {
            ids.push(item[this.delProp])
          }
          ids = ids.join(',')
          this.$ajax.del(this.url.delData, { [this.delProp + 's']: ids }).then(res => {
            this.handleSearchByStatus(res)
          })
        }
      })
    },

    // 查询条件重置
    handleResetSearch () {
      this.getFieldsFromSearchData()
      this.pageNum = 1
      this.handleSearch()
    },

    //从searchData中提取fields
    getFieldsFromSearchData () {
      if (this.searchFormInfos.children) {
        for (let item of this.searchFormInfos.children) {
          //console.log(item.options)
          if (item.hasOwnProperty('options') && item.options.hasOwnProperty('fields')) {
            for (let i = 0; i < item.options.fields.length; i++) {
              let field = item.options.fields[i]
              let value = (item.options.defaultValue !== undefined && item.options.defaultValue.length == 2) ? (item.options.defaultValue[i] != '' ? new Date(item.options.defaultValue[i]).getTime() : item.options.defaultValue[i]) : ''
              this.$set(this.searchFields, field, value)
            }
          } else if (item.field) {
            this.$set(this.searchFields, item.field, item.options.defaultValue !== undefined ? item.options.defaultValue : '')
          }
        }
      }
      //console.log(this.searchFields)
    },

    //从addData中提取field
    getFieldsFromAddData () {
      if (this.addFormInfos.children) {
        for (let item of this.addFormInfos.children) {
          console.log(item.options)
          if (item.hasOwnProperty('options') && item.options.hasOwnProperty('fields')) {
            for (let i = 0; i < item.options.fields.length; i++) {
              let field = item.options.fields[i]
              let value = (item.options.defaultValue !== undefined && item.options.defaultValue.length == 2) ? (item.options.defaultValue[i] != '' ? new Date(item.options.defaultValue[i]).getTime() : item.options.defaultValue[i]) : ''
              this.$set(this.addFields, field, value)
            }
          } else if (item.field) {
            this.$set(this.addFields, item.field, item.options.defaultValue !== undefined ? item.options.defaultValue : '')
          }
        }
      }
    },

    //获取基础select控件数据
    async getBaseData () {
      let promiseArray = []
      for (let item of this.baseCode) {
        promiseArray.push(this.createPromise(item))
      }
      return await Promise.all(promiseArray)
    },

    createPromise (item) {
      let promise
      const that = this
      promise = new Promise(function (resolve, reject) {
        that.$ajax.get(item.url, item.param).then((res) => {
          if (res.code == 200) {
            let arr = []
            if (res.data instanceof Array) {
              arr.push({ label: '全部', value: '' })
              for (let item of res.data) {
                let baseData = {}
                baseData.label = item
                baseData.value = item
                arr.push(baseData)
              }
            } else {
              arr.push({ label: '全部', value: '' })
              for (let key in res.data) {
                let baseData = {}
                baseData.label = res.data[key]
                baseData.value = key
                arr.push(baseData)
              }
            }

            that.baseData[item.for] = arr
            that.originBaseData[item.for] = res.data
            resolve(0)
          }
        })
      })
      return promise
    },

    //设置field
    changeFields (val) {
      console.log(val)
      if (val.name == 'searchForm') {
        this.searchFields = Object.assign(window._.cloneDeep(this.searchFields), val.field)
      } else if (val.name == 'addForm') {
        this.addFields = Object.assign({}, this.addFields, val.field)
        //if(this.isEdit) this.editData = Object.assign(window._.cloneDeep(this.editData),val.field)
      }
    },

    //处理表单按钮点击
    handleButtonClick (to) {
      //console.log(to)
      if (to.from == 'table') {
        if (to.toDo == 'edit') {
          this.addFields = window._.cloneDeep(to.data)
          this.dialogFormVisible = true
          this.isEdit = true
        } else if (to.toDo == 'del') {
          this.handleDelete(to)//删
        } else {
          this.handleOthers && this.handleOthers(to)
        }
      } else if (to.from == 'searchForm') {
        if (to.toDo == 'add') {
          this.getFieldsFromAddData()
          this.dialogFormVisible = true
          this.isEdit = false
        } else if (to.toDo == 'search') {
          this.handleSearch()//查
        } else if (to.toDo == 'reset') {
          this.handleResetSearch()
        } else if (to.toDo == 'export') {
          this.handleExport()
        } else {
          this.handleOthers && this.handleOthers(to)
        }
      } else if (to.from == 'addForm') {
        if (to.toDo == 'save') {
          this.handleSave(to)//增改
        } else if (to.toDo == 'cancel') {
          this.dialogFormVisible = false
          this.addFields = {}
        } else {
          this.handleOthers && this.handleOthers(to)
        }
      } else if (to.from == 'batchForm') {
        if (to.toDo == 'del') {
          this.handleBatchDelete()
        } else if (to.toDo == 'add') {
          this.dialogFormVisible = true
          this.isEdit = false
        } else {
          this.handleOthers && this.handleOthers(to)
        }
      } else {
        this.handleOtherClicks && this.handleOtherClicks(to)
      }
      if (this.isEmitBtnsEvents) this.$emit('btns-dto', to)
    },

    //根据状态刷新列表
    handleSearchByStatus (res) {
      if (res.code == 200) {
        this.$_c.msg(res.message)
        this.handleSearch()
      } else {
        this.$_c.msg(res.message, { type: 'error' })
      }
    },

    //处理对话框关闭
    handleDialogClose (val) {
      this.dialogFormVisible = val
    },

    //定时取数据
    handleInterval () {
      clearInterval(this.timer)
      this.handleSearch()
      this.timer = setInterval(() => {
        this.handleSearch()
      }, this.interval)
    },


    // 导出
    handleExport () {
      //this.$_c.msg('导出测试！')
    },

    //处理table选择
    handleSelectionChange (val) {
      this.multipleSelection = val
      this.handleBatchBtnsStatus && this.handleBatchBtnsStatus(val)
    },

    //处理每页显示多少数据
    handleSizeChange (val) {
      //console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.handleSearch();
    },

    //处理当前页输入
    handleCurrentChange (val) {
      //console.log(`当前页: ${val}`);
      this.pageNum = val;
      this.handleSearch();
    },

    //表格的高度响应处理
    getMaxHeight () {
      let innerHeight = window.innerHeight
      let proportion = (innerHeight < 700) ? 0.6 : 0.7
      this.tableMaxHeight = parseInt(innerHeight * proportion)
    },

    //下载excel,res为要导出的内容，name为文件名
    downloadExcel (res, name) {
      const blob = new Blob([res], {
        type: 'application/vnd.ms-excel;charset=utf-8'
      })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = name + '.xlsx'
      document.body.appendChild(downloadElement)
      downloadElement.click()
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    },
  },
  mounted () {
    this.getFieldsFromSearchData()
    if (this.handleSearchBefore) {
      this.handleSearchBefore().then(res => {
        //console.log(res)
        if (res) this.handleSearch()
      })
    } else {
      this.handleSearch()
    }
    if (this.isOpenInterval) this.handleInterval()

    window.addEventListener('resize', this.getMaxHeight)
  },
  created () {
    this.getMaxHeight()
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.getMaxHeight)
  },
}
export default Crud
